package com.dev.module_zqc_sleep.mvi.ui

import android.content.Intent
import android.content.IntentFilter
import android.icu.text.SimpleDateFormat
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableFloatState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.dev.module_ui_composable.components.MyTopBar
import com.dev.module_ui_composable.picker.MyTimePicker
import com.dev.module_ui_composable.utils.ToastUtils
import com.dev.module_ui_composable.view.ad.BannerAdView
import com.dev.module_zqc_sleep.R
import com.dev.module_zqc_sleep.broadcast.TimeTickReceiver
import com.dev.module_zqc_sleep.mvi.vm.AlarmViewModel
import com.dev.module_zqc_sleep.utils.AlarmUtils.calculateSleepDuration
import java.util.Date
import java.util.Locale

@Composable
fun SettingAlarmScreen(
    alarmViewModel: AlarmViewModel,
    onBackPress: (String) -> Unit,
    onSelectAudio: () -> Unit
) {
    val context = LocalContext.current
    val showTimePicker = remember { mutableStateOf(false) }
    var currentTime by remember { mutableStateOf("") }
    var selectedTime by remember { mutableStateOf("") }
    val sliderPosition = remember { mutableFloatStateOf(0.5f) }
    val checked = remember { mutableStateOf(false) }
    val selectedAudioPair by alarmViewModel.audioPath.collectAsStateWithLifecycle()
    val formatter = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }

    val sleepDurationText = remember(currentTime, selectedTime) {
        calculateSleepDuration(currentTime, selectedTime)
    }

    DisposableEffect(context) {
        currentTime = formatter.format(Date())

        val receiver = TimeTickReceiver {
            currentTime = formatter.format(Date())
        }
        val filter = IntentFilter(Intent.ACTION_TIME_TICK)
        context.registerReceiver(receiver, filter)

        onDispose {
            context.unregisterReceiver(receiver)
        }
    }

    val onSettingClick: () -> Unit = {
        if (selectedTime.isNotEmpty() && selectedAudioPair.first.isNotEmpty()) {
            alarmViewModel.saveAlarmSetting(context, selectedAudioPair.second, checked.value, sliderPosition.floatValue)
            onBackPress(selectedTime)
        } else {
            ToastUtils.showShortToast(context, "请选择起床时间和起床铃声")
        }
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            MyTopBar(title = "设置") { onBackPress(selectedTime) }
        },
        containerColor = Color.White
    ) { innerPadding ->
        SettingItemContent(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
            currentTime = currentTime,
            selectedTime = selectedTime,
            sleepDurationText = sleepDurationText,
            sliderPosition =sliderPosition,
            selectedAudioName = selectedAudioPair.first,
            checked = checked,
            onShowTimePicker = { showTimePicker.value = true },
            onSelectAudio = onSelectAudio,
            onSettingAlarm = onSettingClick
        )
    }

    MyTimePicker(showTimePicker = showTimePicker) { time ->
        selectedTime = time
    }
}

@Composable
private fun SettingItemContent(
    modifier: Modifier = Modifier,
    currentTime: String,
    selectedTime: String,
    sleepDurationText: String,
    sliderPosition: MutableFloatState,
    checked: MutableState<Boolean>,
    selectedAudioName: String,
    onShowTimePicker: () -> Unit,
    onSelectAudio: () -> Unit,
    onSettingAlarm: () -> Unit
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 15.dp),
            verticalArrangement = Arrangement.spacedBy(15.dp)
        ) {
            Text(
                text = "睡眠时长: $sleepDurationText",
                color = Color(0xFF84DCED)
            )

            SettingItemCard {
                Row(
                    modifier = Modifier.weight(2.5f),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Image(
                        painter = painterResource(R.mipmap.m_alarm_ic1),
                        contentDescription = null,
                        modifier = Modifier.wrapContentSize(),
                        contentScale = ContentScale.FillBounds
                    )

                    Text(
                        text = "就寝目标",
                        fontSize = 14.sp
                    )
                }

                Text(
                    text = currentTime.ifEmpty { "00:00" },
                    modifier = Modifier.weight(1f),
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            SettingItemCard(onItemClick = { onShowTimePicker() }) {
                Row(
                    modifier = Modifier.weight(2.5f),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Image(
                        painter = painterResource(R.mipmap.m_alarm_ic2),
                        contentDescription = null,
                        modifier = Modifier.wrapContentSize(),
                        contentScale = ContentScale.FillBounds
                    )

                    Text(
                        text = "起床目标",
                        fontSize = 14.sp
                    )
                }

                Text(
                    text = selectedTime.ifEmpty { "00:00" },
                    modifier = Modifier.weight(1f),
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }

        Column(
            modifier = Modifier
                .padding(top = 30.dp)
                .fillMaxWidth()
                .weight(1f)
                .padding(horizontal = 15.dp),
            verticalArrangement = Arrangement.spacedBy(15.dp)
        ) {
            Text(
                text = "更多设置",
                color = Color(0xFFCCCCCC)
            )

            SettingItemCard(enabled = false) {
                Image(
                    painter = painterResource(R.mipmap.m_alarm_ic3),
                    contentDescription = null,
                    modifier = Modifier.wrapContentSize(),
                    contentScale = ContentScale.FillBounds
                )

                Slider(
                    value = sliderPosition.floatValue,
                    onValueChange = { sliderPosition.floatValue = it },
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 8.dp),
                    valueRange = 0.1f..1f
                )

                Image(
                    painter = painterResource(R.mipmap.m_alarm_ic3),
                    contentDescription = null,
                    modifier = Modifier.wrapContentSize(),
                    contentScale = ContentScale.FillBounds
                )
            }

            SettingItemCard(enabled = false) {
                Text(
                    text = "振动",
                    modifier = Modifier.weight(1f),
                    fontSize = 14.sp,
                    color = Color.Black
                )

                Switch(
                    checked = checked.value,
                    onCheckedChange = {
                        checked.value = it
                    }
                )
            }

            SettingItemCard(onItemClick = { onSelectAudio() }) {
                Image(
                    painter = painterResource(R.mipmap.m_alarm_ic5),
                    contentDescription = null,
                    modifier = Modifier.wrapContentSize(),
                    contentScale = ContentScale.FillBounds
                )
                Text(
                    text = selectedAudioName.ifEmpty { "预设音乐" },
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .weight(1f),
                    fontSize = 14.sp
                )
            }
        }

        Column(
            modifier = Modifier.padding(50.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            BannerAdView()

            FilledTonalButton(
                onClick = { onSettingAlarm() },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp),
                colors = ButtonDefaults.filledTonalButtonColors(
                    containerColor = Color(0xFF706CF6),
                    contentColor = Color.White
                )
            ) {
                Text(text = "保存", fontSize = 18.sp)
            }
        }
    }
}

@Composable
private fun SettingItemCard(
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    onItemClick: () -> Unit = {},
    content: @Composable RowScope.() -> Unit
) {
    Card(
        onClick = { onItemClick() },
        modifier = modifier
            .fillMaxWidth()
            .height(80.dp),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        enabled = enabled
    ) {
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 25.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            content()
        }
    }
}